package cn.cytong.nk0713.services;

import cn.cytong.nk0713.utils.nutz.CustomisedNutDao;
import cn.cytong.rpc.server.NutzRpcService;
import flexjson.JSONSerializer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.nutz.dao.entity.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 日志信息
 */
public class OperatorLog extends NutzRpcService {
    private Logger logger = LoggerFactory.getLogger(OperatorLog.class);
    private CustomisedNutDao nutDao;

    /**
     * 操作日志售卡统计
     * @param params    et      结束时间
     *                  st      开始时间
     *                  opId    操作员Id
     * @return          record(saleCount,userCount)售卡数量，开户数量
     *                  success true or false
     */
    public String count(Map params) {
        Map result = new HashMap();

        String et = (String) params.get("et");
        String st = (String) params.get("st");
        Object opId = params.get("opId");
        try {
            checkNotNull(opId, "操作员信息不存在");
            StringBuffer sb = new StringBuffer("select" +
                    " sum(case serviceType when 10 then 1 else 0 end) -" +
                    "  sum(case serviceType when 19 then 1 else 0 end) AS saleCount," +
                    " sum(case serviceType when 1 then 1 else 0 end) as userCount" +
                    " from OperatorServiceLog ");
            sb.append(" where operator_id = ").append(opId);
            if (StringUtils.isNotBlank(st))
                sb.append(" and serviceAt >= ").append(st);
            if (StringUtils.isNotBlank(et)) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                sb.append(" and serviceAt < ").append(format.format(DateUtils.addDays(format.parse(et), 1)));
            }
            Record record = nutDao.fetchRecord(sb.toString());
            result.put("record", record);
            result.put("success", true);
        } catch (Exception e) {
            logger.error("error in method OperatorLog.count", e);
            result.put("success", false);
            result.put("msg", e.getMessage());
        }
        return new JSONSerializer().serialize(result);
    }

    public String queryOperatorLogs(Map params) {
        Map rtn = new HashMap();
        try {
            String st = (String) params.get("st");
            String et = (String) params.get("et");
            String operatorUsername = (String) params.get("operatorUsername");
            Long operatorId = null;
            if (StringUtils.isNoneEmpty(operatorUsername))
                operatorId = nutDao.fetchLong("select id from Operator where username = ?", operatorUsername);
            if (operatorId == null)
                operatorId = Long.parseLong(params.get("operatorId").toString());

            Integer currentPage = (Integer) params.get("currentPage");
            Integer rowsPerPage = (Integer) params.get("rowsPerPage");

            int count = nutDao.fetchLong("select count(*) from OperatorServiceLog t1 " +
                    "left join card t2 on t1.card_id = t2.id where t1.serviceAt >= ? and t1.serviceAt <= ?" +
                    " and t1.operator_id = ? and (t2.productType=0 or t2.productType=3)", st, et, operatorId).intValue();

            int totalPage = calcTotalPage(rowsPerPage, count);       //总页数
            currentPage = getCurrentPage(currentPage, totalPage);    //有效当前页数

            List<Record> recordList = nutDao.queryPageRecord("select t1.serviceAt,t1.serviceType,t1.fee,t2.cardNo," +
                    "t3.name from OperatorServiceLog t1 left join card t2 on t1.card_id = t2.id " +
                    "left join Customer t3 on t1.customer_id = t3.id where t1.serviceAt >= ? and t1.serviceAt <= ? " +
                    " and t1.operator_id = ? and (t2.productType=0 or t2.productType=3) order by t1.id desc", currentPage, rowsPerPage, st, et, operatorId);


            Record cardCount = nutDao.fetchRecord("select " +
                    "sum(case serviceType when 10 then 1 else 0 end) as saleCount," +
                    "sum(case serviceType when 19 then 1 else 0 end) as cancelCount," +
                    "sum(case serviceType when 1 then 1 else 0 end) as userCount," +
                    "sum(case serviceType when 7 then 1 else 0 end) as renewalCount " +
                    "from (select t1.*,t2.productType from OperatorServiceLog t1 left join card t2 on t1.card_id = t2.id " +
                    "where t1.serviceAt >= ? and t1.serviceAt < ? and t1.operator_id = ? and (t2.productType=0 or t2.productType=3)) a", st, et, operatorId);

            rtn.put("cardCount", cardCount);

            int activeCount = nutDao.fetchLong("select count(*) from OperatorServiceLog t1 " +
                    "left join card t2 on t1.card_id = t2.id where t1.serviceAt >= ? and t1.serviceAt <= ? " +
                    " and t1.operator_id = ? and (t2.productType=0 or t2.productType=3) and t1.serviceType = ?", st, et, operatorId, 10).intValue();    //激活总数

            int reverseCount = nutDao.fetchLong("select count(*) from OperatorServiceLog t1 " +
                    "left join card t2 on t1.card_id = t2.id where t1.serviceAt >= ? and t1.serviceAt <= ? " +
                    " and t1.operator_id = ? and (t2.productType=0 or t2.productType=3) and t1.serviceType = ?", st, et, operatorId, 19).intValue();    //反激活总数

            rtn.put("activeCount", activeCount-reverseCount);
            rtn.put("recordList", recordList);
            rtn.put("totalPage", totalPage);
            rtn.put("page", currentPage);
            rtn.put("count", count);
            rtn.put("success", true);
        } catch (Exception e) {
            logger.error("error in method queryOperatorLogs", e);
            rtn.put("success", false);
            rtn.put("msg", e.getMessage());
        }

        return new JSONSerializer().include("recordList").serialize(rtn);
    }

    /**
     * 计算总页数
     *
     * @param rowsPerPage 每页显示数
     * @param count       总记录数
     * @return 总页数
     */
    public static int calcTotalPage(int rowsPerPage, int count) {
        if (count % rowsPerPage == 0) {
            return count / rowsPerPage;
        } else {
            return count / rowsPerPage + 1;
        }
    }

    /**
     * 获取有效的当前页
     *
     * @param currentPage 查询的页数
     * @param totalPage   总页数
     * @return 有效当前页数
     */
    public static int getCurrentPage(Integer currentPage, int totalPage) {
        if (currentPage == null || currentPage > totalPage || currentPage < 1) {
            return 1;
        } else {
            return currentPage;
        }
    }
}


